package com.abetsy.vben.utils;

import cn.hutool.core.net.URLDecoder;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.abetsy.vben.entity.constant.TMDBConstant;
import com.abetsy.vben.utils.i18n.VbenException;
import com.abetsy.vben.vo.DramaVo;
import lombok.Data;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class FnosUtil {

    private static final String SIGN_KEY = "16CCEB3D-AB42-077D-36A1-F355324E4237";

    private static final String SECRET_KEY = "NDzZTVxnRKP8Z0jXg1VAMonaG8akvh";

    private static final String TRIM_KEY = "Trim-MC-token";

    public static String base = "https://[2409:8a20:4c35:6300:36d3:ab14:971f:8193]:8001";

    public static String token = "3c53f5b7151740baac507d4aaaef89f5";

    private static final String LOGIN_URL = "/v/api/v1/login";

    private static final String SEARCH_URL = "/v/api/v1/scrap/search";

    private FnosUtil() {
    }

    private static FnosUtil instance;

    public static synchronized FnosUtil getInstance() {
        if (instance == null) {
            instance = new FnosUtil();
        }
        return instance;
    }

    public List<DramaVo> searchDrama(String dramaName, HttpServletRequest requestVue) {
        List<DramaVo> dramaVos = new ArrayList<>();
        // 执行查询
        HashMap<String, Object> paramMap = new LinkedHashMap<>();
        paramMap.put("source", "title");
        paramMap.put("source_keyword", dramaName);
        paramMap.put("lan", "zh-CN");
        HttpRequest request = HttpUtil.createPost(base + SEARCH_URL);
        request.header("Authorization", token, true);
        request.header("Cookie", String.format("%s=%s", TRIM_KEY, token), true);
        request.header("Authx", postSign(paramMap, SEARCH_URL), true);
        try (HttpResponse httpResponse = request.body(JSONUtil.toJsonPrettyStr(paramMap)).execute()) {
            if (httpResponse != null && httpResponse.getStatus() == 200) {
                JSONObject jsonObject = JSONUtil.parseObj(httpResponse.body());
                if (jsonObject.getInt("code") == 0) {
                    for (Object data : JSONUtil.parseArray(jsonObject.get("data").toString())) {
                        JSONObject dataObj = JSONUtil.parseObj(data.toString());
                        String sourceId = dataObj.getStr("source_id");
                        if (sourceId != null && sourceId.startsWith("tt")) {
                            DramaVo dramaVo = new DramaVo();
                            dramaVo.setOriginal(Integer.parseInt(sourceId.replace("tt", "")));
                            dramaVo.setTitle(dataObj.getStr("title"));
                            dramaVo.setSource(TMDBConstant.BASE_DRAMA_UI + sourceId.replace("tt", ""));
                            dramaVo.setTime(dataObj.getStr("first_air_date"));
                            dramaVo.setImage(String.format("%s://%s/api/tmdb/image%s", requestVue.getScheme(), requestVue.getHeader("host"), dataObj.getStr("poster_link")));
                            dramaVo.setCount(dataObj.getInt("number_of_seasons"));
                            dramaVos.add(dramaVo);
                        }
                    }
                }else {
                    VbenException.locale("fnos.api.error");
                }
            }
        }catch (Exception e){
            VbenException.locale("fnos.set.error");
        }
        return dramaVos;
    }

    private String postSign(HashMap<String, Object> tt, String et) {
        String rt = JSONUtil.toJsonPrettyStr(JSONUtil.parseObj(tt));
        String st = SecureUtil.md5(URLDecoder.decode(rt.replaceAll("%(?![0-9A-Fa-f]{2})", "%25"), StandardCharsets.UTF_8));
        String it = String.format("%06d", Math.round(new Random().nextDouble() * (1000000 - 100000) + 100000));
        String ot = System.currentTimeMillis() + "";
        String lt = String.join("_", SECRET_KEY, et, it, ot, st, SIGN_KEY);
        return String.format("nonce=%s&timestamp=%s&sign=%s", it, ot, SecureUtil.md5(lt));
    }

    public boolean loginCheck(String url, String username, String password) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("username", username);
        paramMap.put("password", password);
        paramMap.put("app_name", "trimemedia-web");
        try (HttpResponse httpResponse = HttpUtil.createPost(url + LOGIN_URL).body(JSONUtil.toJsonPrettyStr(paramMap)).execute()) {
            if (httpResponse != null && httpResponse.getStatus() == 200) {
                JSONObject jsonObject = JSONUtil.parseObj(httpResponse.body());
                if (jsonObject.getInt("code") == 0) {
                    base = url;
                    token = JSONUtil.parseObj(jsonObject.get("data").toString()).get("token").toString();
                    return true;
                }
            }
        }
        return false;
    }

    public String BaseUrl() {
        return base;
    }

}
